package com.yhy.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;


/**
 * describe:
 *
 * @author helloworldyu
 * @date 2018/5/8
 */
public class StringDatagramClient {
	private final String host;
	private final int port;

	public StringDatagramClient(String host, int port) {
		this.host = host;
		this.port = port;
	}

	public void start()
			throws Exception {
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			Bootstrap b = new Bootstrap();
			b.group(group)
					.channel(NioDatagramChannel.class)
					.option(ChannelOption.SO_BROADCAST,true)
					.handler(new ChannelInitializer<NioDatagramChannel>() {
						@Override
						protected void initChannel(NioDatagramChannel ch) throws Exception {
							ch.pipeline()
									.addLast(new DatagramStringEncoder(host,port))
									.addLast(new DatagramStringDecoder())
									.addLast(new ServerHandler())
									.addLast(new ServerHandler2());
						}
					});
			ChannelFuture f = b.bind(1234).sync();
			System.out.println("链接成功");
			f.channel().writeAndFlush(new String("nihao"));
			f.channel().closeFuture().sync();
		} finally {
			group.shutdownGracefully().sync();
		}
	}

	public static void main(String[] args)
			throws Exception {
		final String host = "127.0.0.1";
		final int port = 8080;

		new StringDatagramClient(host, port).start();
	}
}